package com.lianyu507.api;

import com.lianyu507.bean.LoginForm;
import com.lianyu507.bean.LoginResult;
import com.lianyu507.enums.ErrorTypeEnum;
import com.lianyu507.pojo.MbUser;
import com.lianyu507.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/portal")
public class LoginController extends BaseController{
	
	@Autowired
	private LoginService loginService;


	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> login(HttpSession session,@RequestBody LoginForm loginForm){
		try {

			if(loginForm.getToken()!=null){
				Object obj=session.getAttribute(loginForm.getToken());
				if(obj==null){
					return failedResult(ErrorTypeEnum.VALIDATE_ERROR,"请重新登录");
				}
				return this.successResult(obj);
			}else{
				LoginResult result=loginService.login(loginForm.getUserName(), loginForm.getPassword());
				session.setAttribute(result.getToken(), result);
				return successResult(result);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return failedResult(ErrorTypeEnum.NOT_FOUND,e.getMessage());
		}
	}

	@RequestMapping(value = "/login/needLogin")
	@ResponseBody
	public  Map<String,Object> needLogin(){
		return failedResult(ErrorTypeEnum.NEED_LOGIN,"请重新登录!");
	}


}
	
